﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Entities.Admin;
using WindowsForms.Admin;
using System.Collections;

namespace WindowsForms
{
    public partial class UcGiaiDau : UserControl
    {

        public bool kt = true;
        int magiaidau;
        public GiaiDau giaidau = new GiaiDau();
        int iCellHeight, iHeaderHeight;
        double iTotalWidth;
        bool bNewPage, bFirstPage;
        public StringFormat strFormat;
        public ArrayList arrColumnWidths = new ArrayList();
        public ArrayList arrColumnLefts = new ArrayList();
        public int iCount;
        public UcGiaiDau()
        {
            InitializeComponent();
            datagiaidau.AutoGenerateColumns = false;
        }

        private void btnrefresh_Click(object sender, EventArgs e)
        {
            LoadGiaiDau(GiaiDau.Objects.All().ToList());

        }
        private void LoadGiaiDau(List<GiaiDau> ds)
        {
            datagiaidau.DataSource = ds;

        }

        private void datagiaidau_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int magd;
            bool state;

            try
            {
                if (e.ColumnIndex == 4)
                {

                    magd = Convert.ToInt32(datagiaidau[0, e.RowIndex].Value);
                    try
                    {
                        state = GiaiDau.Objects.Delete(p => p.MaGiaiDau == magd);
                        if (state)
                        {

                            MessageBox.Show("Xóa  thành công");
                            LoadGiaiDau(GiaiDau.Objects.All().ToList());
                        }
                        else MessageBox.Show("xóa thất bại");

                    }
                    catch (Exception)
                    {

                        MessageBox.Show("Do tính ràng buộc dử liệu nên giải đấu vừa chọn không thể xóa ");
                    }


                }
                if (e.ColumnIndex == 5)
                {

                    magiaidau = Convert.ToInt32(datagiaidau[0, e.RowIndex].Value);
                    GiaiDau gd1 = GiaiDau.Objects.GetById(magiaidau);
                    try
                    {
                        tbmgd.Text = magiaidau + "";
                        tbgiaidau.Text = gd1.TenGiaiDau;
                        dtpngayktranh.Value = gd1.ThoiGianBatDau;
                    }
                    catch (Exception)
                    {

                        
                    }


                }
            }
            catch (Exception)
            {


            }



        }

        private void btntim_Click(object sender, EventArgs e)
        {
            FormTimGiaiDau fr = new FormTimGiaiDau();

            fr.FormClosed += new FormClosedEventHandler(fr_FormClosed);
            fr.ShowDialog();
        }

        void fr_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (FormTimGiaiDau.state)
            {
                string data = FormTimGiaiDau.dataFind;
                if (!String.IsNullOrWhiteSpace(data))
                {
                    List<GiaiDau> ds = GiaiDau.Objects.Find(p => p.TenGiaiDau.Contains(data)).ToList();
                    LoadGiaiDau(ds);
                }
            }
        }

        private void btin_Click(object sender, EventArgs e)
        {
            //PrintPreviewDialog printDialog = new PrintPreviewDialog();
            PrintDialog printDialog = new PrintDialog();
            printDialog.Document = printDocument1;
            printDialog.UseEXDialog = true;


            //Get the document

            if (DialogResult.OK == printDialog.ShowDialog())
            {

                printDocument1.DocumentName = "Test Page Print";
                printDocument1.Print();

            }
        }
        private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            try
            {
                strFormat = new StringFormat();
                strFormat.Alignment = StringAlignment.Near;
                strFormat.LineAlignment = StringAlignment.Center;
                strFormat.Trimming = StringTrimming.EllipsisCharacter;

                arrColumnLefts.Clear();
                arrColumnWidths.Clear();
                iCellHeight = 0;
                iCount = 0;
                bFirstPage = true;
                bNewPage = true;

                // Calculating Total Widths
                iTotalWidth = 0;
                //foreach (DataGridViewColumn dgvGridCol in dataGridViewtk.Columns)
                //{
                //    iTotalWidth += dgvGridCol.Width;
                //}
                for (int k = 0; k < datagiaidau.Columns.Count - 2; k++)
                {
                    iTotalWidth += datagiaidau.Columns[k].Width;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            int iRow = 0;


            try
            {
                //Set the left margin
                int iLeftMargin = e.MarginBounds.Left;
                //Set the top margin
                int iTopMargin = e.MarginBounds.Top;
                //Whether more pages have to print or not
                bool bMorePagesToPrint = false;
                int iTmpWidth = 0;
                int iCount = 0;

                //For the first page to print set the cell width and header height
                if (bFirstPage)
                {
                    //foreach (DataGridViewColumn GridCol in dataGridViewtk.Columns)
                    //{
                    //    iTmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /
                    //        (double)iTotalWidth * (double)iTotalWidth *
                    //        ((double)e.MarginBounds.Width / (double)iTotalWidth))));

                    //    iHeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
                    //        GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11;

                    //    // Save width and height of headers
                    //    arrColumnLefts.Add(iLeftMargin);
                    //    arrColumnWidths.Add(iTmpWidth);
                    //    iLeftMargin += iTmpWidth;
                    //}
                    for (int k = 0; k < datagiaidau.ColumnCount - 2; k++)
                    {
                        iTmpWidth = (int)(Math.Floor((double)((double)datagiaidau.Columns[k].Width /
                            (double)iTotalWidth * (double)iTotalWidth *
                            ((double)e.MarginBounds.Width / (double)iTotalWidth))));

                        iHeaderHeight = (int)(e.Graphics.MeasureString(datagiaidau.Columns[k].HeaderText,
                            datagiaidau.Columns[k].InheritedStyle.Font, iTmpWidth).Height) + 11;

                        // Save width and height of headers
                        arrColumnLefts.Add(iLeftMargin);
                        arrColumnWidths.Add(iTmpWidth);
                        iLeftMargin += iTmpWidth;
                    }
                }

                //Loop till all the grid rows not get printed
                while (iRow <= datagiaidau.Rows.Count - 1)
                {
                    DataGridViewRow GridRow = datagiaidau.Rows[iRow];
                    //Set the cell height
                    iCellHeight = GridRow.Height + 5;

                    //Check whether the current page settings allows more rows to print
                    if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
                    {
                        bNewPage = true;
                        bFirstPage = false;
                        bMorePagesToPrint = true;
                        break;
                    }
                    else
                    {
                        if (bNewPage)
                        {
                            //Draw Header
                            e.Graphics.DrawString("Acount Customer",
                                new Font(datagiaidau.Font, FontStyle.Bold),
                                Brushes.Black, e.MarginBounds.Left,
                                e.MarginBounds.Top - e.Graphics.MeasureString("Acount Customer",
                                new Font(datagiaidau.Font, FontStyle.Bold),
                                e.MarginBounds.Width).Height - 13);

                            String strDate = DateTime.Now.ToLongDateString() + " " +
                                DateTime.Now.ToShortTimeString();
                            //Draw Date
                            e.Graphics.DrawString(strDate,
                                new Font(datagiaidau.Font, FontStyle.Bold), Brushes.Black,
                                e.MarginBounds.Left +
                                (e.MarginBounds.Width - e.Graphics.MeasureString(strDate,
                                new Font(datagiaidau.Font, FontStyle.Bold),
                                e.MarginBounds.Width).Width),
                                e.MarginBounds.Top - e.Graphics.MeasureString("Acount Customer",
                                new Font(new Font(datagiaidau.Font, FontStyle.Bold),
                                FontStyle.Bold), e.MarginBounds.Width).Height - 13);

                            //Draw Columns                 
                            iTopMargin = e.MarginBounds.Top;
                            //foreach (DataGridViewColumn GridCol in dataGridViewtk.Columns)
                            //{
                            //    e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                            //        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                            //        (int)arrColumnWidths[iCount], iHeaderHeight));

                            //    e.Graphics.DrawRectangle(Pens.Black,
                            //        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                            //        (int)arrColumnWidths[iCount], iHeaderHeight));

                            //    e.Graphics.DrawString(GridCol.HeaderText,
                            //        GridCol.InheritedStyle.Font,
                            //        new SolidBrush(GridCol.InheritedStyle.ForeColor),
                            //        new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
                            //        (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
                            //    iCount++;
                            //}
                            for (int l = 0; l < datagiaidau.Columns.Count - 2; l++)
                            {
                                e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                                    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight));

                                e.Graphics.DrawRectangle(Pens.Black,
                                    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight));

                                e.Graphics.DrawString(datagiaidau.Columns[l].HeaderText,
                                    datagiaidau.Columns[l].InheritedStyle.Font,
                                    new SolidBrush(datagiaidau.Columns[l].InheritedStyle.ForeColor),
                                    new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
                                iCount++;
                            }
                            bNewPage = false;
                            iTopMargin += iHeaderHeight;
                        }
                        iCount = 0;
                        //Draw Columns Contents                
                        //foreach (DataGridViewCell Cel in GridRow.Cells)
                        //{
                        //    if (Cel.Value != null)
                        //    {
                        //        e.Graphics.DrawString(Cel.Value.ToString(),
                        //            Cel.InheritedStyle.Font,
                        //            new SolidBrush(Cel.InheritedStyle.ForeColor),
                        //            new RectangleF((int)arrColumnLefts[iCount],
                        //            (float)iTopMargin,
                        //            (int)arrColumnWidths[iCount], (float)iCellHeight),
                        //            strFormat);
                        //    }
                        //    //Drawing Cells Borders 
                        //    e.Graphics.DrawRectangle(Pens.Black,
                        //        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                        //        (int)arrColumnWidths[iCount], iCellHeight));
                        //    iCount++;
                        //}
                        for (int t = 0; t < GridRow.Cells.Count - 2; t++)
                        {
                            if (GridRow.Cells[t].Value != null)
                            {
                                e.Graphics.DrawString(GridRow.Cells[t].Value.ToString(),
                                    GridRow.Cells[t].InheritedStyle.Font,
                                    new SolidBrush(GridRow.Cells[t].InheritedStyle.ForeColor),
                                    new RectangleF((int)arrColumnLefts[iCount],
                                    (float)iTopMargin,
                                    (int)arrColumnWidths[iCount], (float)iCellHeight),
                                    strFormat);
                            }
                            //Drawing Cells Borders 
                            e.Graphics.DrawRectangle(Pens.Black,
                                new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                (int)arrColumnWidths[iCount], iCellHeight));
                            iCount++;
                        }
                    }

                    iRow++;
                    iTopMargin += iCellHeight;
                }
                //If more lines exist, print another page.
                if (bMorePagesToPrint)
                    e.HasMorePages = true;
                else
                    e.HasMorePages = false;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK,
                   MessageBoxIcon.Error);
            }

        }

        private void btnluu_Click(object sender, EventArgs e)
        {
            string tengd = tbgiaidau.Text;
            DateTime nkt = dtpngayktranh.Value;

            GiaiDau gd = new GiaiDau();
            if (!String.IsNullOrWhiteSpace(tbmgd.Text))
                gd.MaGiaiDau=Convert.ToInt32(tbmgd.Text);
            else gd.MaGiaiDau=0;
           
            gd.TenGiaiDau = tengd;
            gd.ThoiGianBatDau = nkt;
            gd.ThoiGianKetThuc = dtpketthuc.Value;
            if (dtpketthuc.Value > dtpngayktranh.Value)
            {
                if (!String.IsNullOrWhiteSpace(tengd))
                {
                    if (Convert.ToInt32(tbmgd.Text) == 0)
                    {
                        int kq = GiaiDau.Objects.AddWithIdentity(gd);
                        if (kq > 0)
                        {
                            MessageBox.Show("Thêm Thành Công");
                            LoadGiaiDau(GiaiDau.Objects.All().ToList());
                        }
                        else MessageBox.Show("Thêm Thất Bại");
                    }
                    else
                    {


                        bool q = GiaiDau.Objects.Update(gd);
                        if (q)
                        {
                            MessageBox.Show("Cập Nhật Thành Công");
                            LoadGiaiDau(GiaiDau.Objects.All().ToList());
                        }
                        else MessageBox.Show("Cập Nhật Thất Bại");


                    }
                }
                else MessageBox.Show("Tên Giải Đấu Không Được Để Trống");
            }
            else MessageBox.Show("Nhập Ngày Bắt Đầu Và ngày Kết Thúc Chưa Đúng ngày Kết Thúc > Ngày Bắt Đầu");





        }

        private void btnreset_Click(object sender, EventArgs e)
        {
            tbmgd.Text = "0";
            tbgiaidau.Text = "";
            dtpngayktranh.Value = DateTime.Now;
        }
    }
}
